import 'dart:async';

import 'package:star_author/config/app.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/good_video_status_event.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/num_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/views/pic_swiper/pic_swiper.dart';
import 'package:star_author/views/stream/stream.dart';
import 'package:star_author/widgets/constraints_widget.dart';
import 'package:star_author/widgets/image_widget.dart';
import 'package:star_author/widgets/swiper_view_widget.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_aliplayer/flutter_aliplayer.dart';
import 'package:flutter_aliplayer/flutter_aliplayer_factory.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';

class DetailPreviewWidget extends StatefulWidget {
  final List images;
  final List videos;
  final bool sonance;
  final String status;
  final List<dynamic> studios;
  final BorderRadius? borderRadius;
  Function(int index) indexChanged;
  final double? indicatorBottom;

  DetailPreviewWidget({
    Key? key,
    this.images = const [],
    this.videos = const [],
    this.sonance = false,
    this.status: "",
    this.studios: const [],
    this.borderRadius,
    required this.indexChanged,
    this.indicatorBottom,
  }) : super(key: key);

  _DetailPreviewWidgetState createState() => _DetailPreviewWidgetState();
}

class _DetailPreviewWidgetState extends State<DetailPreviewWidget> {
  int _currentSwiper = 0;

  FlutterAliplayer player = FlutterAliPlayerFactory.createAliPlayer(
    playerId: getRandomString(8),
  );

  bool showIcon = false; //显示播放按钮

  void onSwiperChange(v) {
    if (v < widget.videos.length) {
      //视频暂停
      player.pause();
      showIcon = true;
    }
    update(() {
      _currentSwiper = v;
      widget.indexChanged(_currentSwiper);
    });
  }

  update(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  //播放
  play() {
    showIcon = false;
    player.play();
    update(() {});
  }

  //是否有可以播放地址
  bool get canPlay {
    return (widget.videos.length) > 0;
  }

  bool loading = false;

  StreamSubscription? subscription;

  @override
  void initState() {
    super.initState();
    FlutterAliplayer.enableConsoleLog(true);
    FlutterAliplayer.enableMix(true);
    player.setCacheConfig(App.ali_setting);
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      initImage();
      for (dynamic video in widget.videos) {
        widget.images.insert(0, video);
      }
      init();
    });
  }

  bool is_paused = false;

  init() async {
    if (canPlay) {
      LogUtil.v("widget.videos[0]:${widget.videos[0]}");
      update(() {
        loading = true;
      });
      player.setUrl(widget.videos[0]);
      //准备成功
      player.setOnPrepared((playerId) {
        player.setVolume(widget.sonance ? 1 : 0);
        //多码率切换并自适应
        player.selectTrack(-1);
        //初始化需要播放
        player.setLoop(autoPlay);
        player.play();
        update(() {
          showIcon = false;
          loading = false;
        });
      });
      player.setOnStateChanged((newState, playerId) {
        switch (newState) {
          //正在播放
          case FlutterAvpdef.AVPStatus_AVPStatusStarted:
            LogUtil.v("播放");
            update(() {
              loading = false;
              is_paused = false;
            });
            break;
          //播放暂停
          case FlutterAvpdef.AVPStatus_AVPStatusPaused:
            LogUtil.v("暂停");
            update(() {
              is_paused = true;
              loading = false;
            });
            break;
          default:
        }
      });
      //播放器事件信息回调，包括buffer、当前播放进度等等信息，根据infoCode来判断，对应FlutterAvpdef.infoCode
      player.setOnInfo((infoCode, extraValue, extraMsg, playerId) {
        if (infoCode == FlutterAvpdef.CURRENTPOSITION) {
          // LogUtil.v(
          //     "infoCode:$infoCode,extraValue:$extraValue,extraMsg:$extraMsg,playerId:$playerId");
          int current = NumUtil.divide(extraValue ?? 1000, 1000).toInt();
          // LogUtil.v("当前播放:${current}");
        }
      });
      player.prepare();
    }

    subscription =
        GlobalEventBus().bus.on<GoodsVideoStatusEvent>().listen((event) {
      update(() {
        showIcon = true;
        player.pause();
      });
    });
  }

  //预加载图片
  initImage() async {
    widget.images.forEach((element) {
      if (element.toString().isNotEmpty) {
        precacheImage(
          CachedNetworkImageProvider(element ?? ""),
          Get.context!,
        ).catchError((e) {
          LogUtil.v("预加载图片失败:${e.toString()}");
        });
      }
    });
  }

  bool autoPlay = true; //自动播放;

  @override
  void dispose() {
    super.dispose();
    try {
      player.destroy();
    } catch (e) {
      LogUtil.v(e.toString());
    }
    subscription?.cancel();
  }

  Widget loadingWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          alignment: Alignment.center,
          child: Text(
            '加载中',
            style: TextStyle(fontSize: 18.sp, color: Colors.white),
          ),
        ),
        SizedBox(
          height: 5,
        ),
        StreamLoadingWidget(
          size: 33,
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    if ((widget.images.length) == 0 && (widget.videos.length) == 0) {
      return ConstraintsWidget(width: '100vw', height: '100vw');
    }
    return ConstraintsWidget(
      width: '100vw',
      height: '100vw',
      child: Container(
          child: Stack(
        children: [
          SwiperViewWidget(
            onChange: onSwiperChange,
            children: List.generate(widget.images.length, (index) {
              String image = widget.images[index];
              if (index < widget.videos.length) {
                return Stack(
                  children: [
                    buildVideoPlayWidget(index),
                    if (loading)
                      Container(
                        color: Colors.black,
                        width: Get.width,
                        height: Get.width,
                        child: loadingWidget(),
                      ),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        width: Get.width,
                        height: Get.width,
                        color: Colors.transparent,
                      ),
                      onTap: () {
                        LogUtil.v("is_paused:$is_paused");
                        if (!is_paused) {
                          //播放
                          showIcon = true;
                          player.pause();
                          update(() {});
                        } else {
                          toPreViewDialog();
                        }
                        update(() {});
                      },
                    ),
                    // //是否显示播放按钮
                    Center(
                      child: Visibility(
                        visible: showIcon,
                        child: InkWell(
                          child: RoucesUtil.getAssetsIcon('common/play', 80.w),
                          onTap: () {
                            play();
                          },
                        ),
                      ),
                    ),
                  ],
                );
              } else {
                if ((widget.images.length) == 0) {
                  return Container();
                }
                return Stack(
                  children: [
                    GestureDetector(
                      onTap: () {
                        toPreViewDialog();
                      },
                      child: ConstraintsWidget(
                        width: '100vw',
                        height: '100vw',
                        child: Container(
                          child: ImageWithPlaceHolder(
                            cover: widget.images[index] ?? "",
                            fit: BoxFit.scaleDown,
                            radius: 0,
                          ),
                          decoration: BoxDecoration(
                              color: Colors.black,
                              borderRadius: widget.borderRadius),
                        ),
                      ),
                    ),
                  ],
                );
              }
            }),
          ),
          Positioned(
            child: Visibility(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.w),
                child: Text(
                  '${_currentSwiper + 1}/${widget.images.length}',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.white,
                  ),
                ),
                decoration: BoxDecoration(
                  color: Color(0x80000000),
                  borderRadius: BorderRadius.circular(15),
                ),
              ),
              visible: widget.images.length > 0,
            ),
            right: 12.w,
            bottom: widget.indicatorBottom ?? 24.w,
          )
        ],
      )),
    );
  }

  ///4、设置播放源
  ///说明：STS 播放方式，vid、region、accessKeyId、accessKeySecret、securityToken 为必填，其他参数可选
  ///     AUTH 播放方式，vid、region、playAuth 为必填，其他参数可选
  /// 每个 Map 对应的key 在 flutter 的 Demo 的 config.dart 中查看，fAliplayer 为播放器对象，如果还未创建，参考后续文档创建播放器
  void onViewPlayerCreated(viewId) async {
    player.setPlayerView(viewId);
  }

  //视频播放组件
  Widget buildVideoPlayWidget(index) {
    return Container(
      width: Get.width,
      height: Get.width,
      decoration: BoxDecoration(
        borderRadius: widget.borderRadius,
        color: ColorConf.black,
      ),
      child: Center(
        child: AliPlayerView(
          onCreated: onViewPlayerCreated,
          x: 0,
          y: 0,
          width: Get.width,
          height: Get.width,
        ),
      ),
    );
  }

  toPreViewDialog() {
    var images = List.from(widget.images);
    if (widget.videos.length > 0) {
      images.removeWhere((element) => element == widget.videos[0]);
    }
    Get.to(PicSwiperPage(
      images: images,
      index: _currentSwiper,
      videos: widget.videos,
    ));
  }
}
